package com.meishij.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.meishij.R;
import com.meishij.customerview.GuoLoadDialog;
import com.meishij.entry.ShihuaEntry;
import com.meishij.server.ShiHuaServer;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/10/12.
 * 我是youngKaka 我的心愿是世界和平
 */

public class ShiHua_New_Main_VP_Adpater extends RecyclerView.Adapter<ShiHua_New_Main_VP_Adpater.ViewHolder> implements ViewPager.OnPageChangeListener, RadioGroup.OnCheckedChangeListener, Callback<ShihuaEntry> {

    private Context context;
    private List<Object> list;
    private int[] layout_id;

    private ShiHua_Banner_VP_Adapter shiHua_banner_vp_adapter;
    private ShiHua_Column_Adpater shiHua_column_adpater;
    private ShiHua_HotTopic_Adpater shiHua_hotTopic_adpater;


    //轮播相关
    private ImageView point_view;
    private static ImageView tranx_imageView;
    private static ViewPager ban_vPager;

    private static RecyclerView hot_new_recyclerView;

    private ShiHuaServer shiHuaServer;
    private boolean isFirst = true;

    private static LinearLayout point_container;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    int currentItem = ban_vPager.getCurrentItem();
                    ban_vPager.setCurrentItem(++currentItem);
                    handler.sendEmptyMessageDelayed(0, 5000);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private Call<ShihuaEntry> shihuaEntry;
    private GuoLoadDialog loadingDialogFirst;


    public ShiHua_New_Main_VP_Adpater(Context context, List<Object> list, int[] layout_id) {
        this.context = context;
        this.list = list;
        this.layout_id = layout_id;
        loadingDialogFirst = new GuoLoadDialog(context, R.style.MyDialog);
        loadingDialogFirst.setCanceledOnTouchOutside(false);
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return layout_id[0];
        } else if (position == 1) {
            return layout_id[1];
        } else if (position == 2) {
            return layout_id[2];
        } else if (position == 3) {
            return layout_id[3];
        }
        return -1;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, viewType, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (position == 0) {
            shiHua_banner_vp_adapter = new ShiHua_Banner_VP_Adapter(context, (List<ShihuaEntry.Activities2Bean>) list.get(0));
            holder.banner_viewPager.setAdapter(shiHua_banner_vp_adapter);
            if (holder.point_layout.getChildCount() == 0) {
                setWhitePointsLayout(holder);
            }
            holder.banner_viewPager.setOnPageChangeListener(this);
        } else if (position == 1) {
            holder.column_layout.setLayoutManager(new GridLayoutManager(context, 5));
            shiHua_column_adpater = new ShiHua_Column_Adpater(context, (List<ShihuaEntry.ColumnBean>) list.get(1));
            holder.column_layout.setAdapter(shiHua_column_adpater);
        } else if (position == 2) {
            holder.hot_new_radioGroup.setOnCheckedChangeListener(this);
            ((RadioButton) holder.hot_new_radioGroup.getChildAt(0)).setChecked(true);
        } else if (position == 3) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(context);
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            holder.recyler_hot_topic.setLayoutManager(layoutManager);
            shiHua_hotTopic_adpater = new ShiHua_HotTopic_Adpater(context, ((List<ShihuaEntry.HotTopicBean>) list.get(3)));
            holder.recyler_hot_topic.setAdapter(shiHua_hotTopic_adpater);
        }
    }

    public void addNewData(int index, Object object) {
        list.add(index, object);
        notifyItemInserted(index);
    }

    public void remove(int index) {
        list.remove(index);
        notifyItemRemoved(index);
    }

    public void addHotTopicAll(List<ShihuaEntry.HotTopicBean> beanList){
        shiHua_hotTopic_adpater.addAll(beanList);
    }

    private void setWhitePointsLayout(final ViewHolder viewHolder) {
        for (int i = 0; i < ((List<ShihuaEntry.Activities2Bean>) list.get(0)).size(); i++) {
            point_view = new ImageView(context);
            point_view.setImageResource(R.drawable.shihua_vp_point_shape_unchecked);
            int point_padding = (int) context.getResources().getDimension(R.dimen.padding_point);
            point_view.setPadding(point_padding, 0, point_padding, 0);
            viewHolder.point_layout.addView(point_view);
        }
        viewHolder.point_layout.post(new Runnable() {
            @Override
            public void run() {
                viewHolder.tranx_view.setVisibility(View.VISIBLE);
                ViewCompat.setTranslationX(viewHolder.tranx_view, viewHolder.point_layout.getLeft() + point_view.getPaddingLeft());
            }
        });
        handler.sendEmptyMessageDelayed(0, 5000);
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        float value = point_container.getLeft() + (position - 1 + positionOffset) * point_view.getWidth() + point_view.getPaddingLeft();
        value = Math.max(value, point_container.getLeft());
        value = Math.min(value, point_container.getRight() - point_view.getPaddingRight());
        ViewCompat.setTranslationX(tranx_imageView, value);
    }

    @Override
    public void onPageSelected(int position) {
        PagerAdapter adapter = ban_vPager.getAdapter();
        if (position == 0) {
            ban_vPager.setCurrentItem(adapter.getCount() - 2, false);
        } else if (position == adapter.getCount() - 1) {
            ban_vPager.setCurrentItem(1, false);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (!isFirst) {
            String sort = null;
            //如果有之前的请求的先取消
            if (shihuaEntry != null) {
                shihuaEntry.cancel();
            }
            switch (checkedId) {
                case R.id.rb_shihua_new:

                    ((RadioButton) group.getChildAt(0)).setChecked(true);
                    sort = "time";
                    break;
                case R.id.rb_shihua_hot:
                    ((RadioButton) group.getChildAt(1)).setChecked(true);
                    sort = "hot";
                    break;
            }
            loadingDialogFirst.show();
            Retrofit build = new Retrofit.Builder().baseUrl("http://api.meishi.cc/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            shiHuaServer = build.create(ShiHuaServer.class);
            shihuaEntry = shiHuaServer.getShihuaEntry(sort);
            shihuaEntry.enqueue(this);
        }
        isFirst = false;
    }



    @Override
    public void onResponse(Call<ShihuaEntry> call, Response<ShihuaEntry> response) {
        if (hot_new_recyclerView != null) {
            if(loadingDialogFirst.isShowing()){
                loadingDialogFirst.dismiss();
            }
            ShihuaEntry body = response.body();
            shiHua_hotTopic_adpater.removeData();
            shiHua_hotTopic_adpater.addAll(body.getHot_topic());
        }
    }

    @Override
    public void onFailure(Call<ShihuaEntry> call, Throwable t) {
        Toast.makeText(context, "吃的太撑了 稍后再试试吧", Toast.LENGTH_SHORT).show();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {


        LinearLayout point_layout;
        ImageView tranx_view;
        ViewPager banner_viewPager;

        RecyclerView column_layout;

        RecyclerView recyler_hot_topic;

        RadioGroup hot_new_radioGroup;

        public ViewHolder(View itemView) {
            super(itemView);
            //轮播图相关
            banner_viewPager = ((ViewPager) itemView.findViewById(R.id.viewpager_shihua_banner));
            tranx_view = ((ImageView) itemView.findViewById(R.id.view_vp_shihua_transx));
            point_layout = ((LinearLayout) itemView.findViewById(R.id.linear_shihua_point));
            if (banner_viewPager != null) {
                ban_vPager = banner_viewPager;
                tranx_imageView = tranx_view;
                point_container = point_layout;
            }

            //column相关
            column_layout = ((RecyclerView) itemView.findViewById(R.id.recyler_shihua_column));

            //hot_new相关
            hot_new_radioGroup = ((RadioGroup) itemView.findViewById(R.id.shihua_radiogroup));

            //hot_topic相关
            recyler_hot_topic = ((RecyclerView) itemView.findViewById(R.id.recyler_shihua_hot_topic));
            if (recyler_hot_topic != null) {
                hot_new_recyclerView = recyler_hot_topic;
            }
        }
    }

}
